瀏覽器自動化(5) Selenium + Scrapy

安裝模塊

1
2
selenium
scrapy
  1. selenium
    主要先用於登入或js互動,剩餘的在使用scrapy進行爬取。

  2. scrapy

Scrapy 是一个爬蟲框架,同時支持異步、多線程、速度非常快、高效,適合爬取海量數據及一層一層的爬取,

官方文檔

如何使用

  • 命令行調試
1
2
3
4
5
6
7
8
9
10
scrapy shell https://doc.scrapy.org/en/latest/_static/selectors-sample1.html
# 會進入交互模式
>>> response.url # 查看當前url
'https://doc.scrapy.org/en/latest/_static/selectors-sample1.html'
>>> response.status # 查看response狀態
200
>>> response.selector.xpath('//title/text()') # 選擇xpath
[<Selector (text) xpath=//title/text()>]
>>> sel.xpath(".//a//@href").extract() # 獲取所有a標籤的url
['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html']
  • python 調試
1
2
3
4
5
6
7
8
9
10
11
12
from selenium import webdriver
from scrapy.selector import Selector

browser = webdriver.Chrome()

browser.get("https://w3.iiiedu.org.tw/")

sel = Selector(text=browser.page_source)

titles = sel.xpath(".//*[@id='centerBodyBox_seminar']//a//text()").extract()

print([t for t in titles])

輸出:

1
2
3
4
5
6
7
8
9
10
11
12
13
['<免費研討會> FB行銷@在地生活圈研討會',
'AR/VR創新應用與視覺優化講座',
'【免費】數位轉型系列講座:數位轉型趨勢和行動方案解析',
'【免費】數位轉型系列講座:數位轉型勢在必行',
'【免費】數位轉型系列講座:AIoT切入智慧醫療與照護的下一波革命',
'【免費】數位轉型系列講座: AI電腦視覺讓你看得更清楚',
'【免費】數位轉型系列講座:AI塑造新零售、新體驗',
'【免費】數位轉型系列講座:AI金融科技的新突破 ',
'【免費】數位轉型系列講座:AI迎向精準行銷的數位革命',
'【免費】數位轉型系列講座:深度學習與各類影像應用',
'【免費】數位轉型系列講座: 數位轉型怎麼做?從企業戰略到人力資本之導入步驟及方法',
'【免費】數位轉型系列講座:AI啟動無人機的未來商業',
'【免費】數位轉型系列講座: AIoT產業智慧轉型的發展模式']

啟動

  • 新建專案項目

建立專案

1
scrapy startproject tutorial

查看目錄

在終端輸入命令

1
tree tutorial

新建一個myspider.py

1
2
3
4
5
6
7
8
9
10
11
12
13
tutorial/
├── tutorial
│   ├── __init__.py
│   ├── items.py
│   ├── middlewares.py
│   ├── pipelines.py
│   ├── __pycache__
│   ├── settings.py
│   └── spiders
│   ├── __init__.py
│ ├── myspider.py # 新建
│   └── __pycache__
└── scrapy.cfg

myspider.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import scrapy
from selenium import webdriver
from scrapy.selector import Selector
import datetime

class mySpider(scrapy.Spider):
name = "mySpider"

start_urls = ["https://doc.scrapy.org/en/latest/_static/selectors-sample1.html"]

def __init__(self):
# 定義webdriver
self.browser = webdriver.Chrome()


def parse(self, response):
# 先由self.browser進行請求
self.browser.get(response.url)

# 用scrapy選擇器獲取selenium的頁面源代碼
sel = Selector(text=self.browser.page_source)

baseurl = sel.xpath('//base/@href').extract_first()
# 'http://example.com/'

links = sel.xpath(".//a//@href").extract()
# ['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html']

for i in links:
request = scrapy.Request(baseurl + i,
callback=self.parse_2,
)

def parse_2(self, response):
'''進入下一個頁面'''
print(response.url)

執行

scrapy crawl
name為mySpider.py裡頭定義的name,並非腳本或項目名。

1
scrapy crawl mySpider

小結

scrapy除了使用上比較繁瑣一點,基本上使用上沒什麼缺點。